import datetime
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from cars.models import Car, MthCar
from cars.serializers import CarDetSerl, MthCarSerl
from teacher.auth import TeacherJWT
from visitor.auth import VisitorJWT
from student.auth import StudentJWT
from mgmt import pagination
from ymiot import views as ymiot_api
from cars import tasks as cartask
from cars.models import carTypeList


class VisitorLstApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        status = request.GET.get("status")
        carList = Car.objects.filter(status=status)
        carLst = []
        for carItem in carList:
            carItm = {}
            carItm["id"] = carItem.id
            carItm["plate"] = carItem.plate
            carLst.append(carItm)
        # 1. 实例化分页器对象
        page_obj = pagination.PageNumberPagination()
        # 2. 使用自己配置的分页器调用分页方法进行分页
        page_data = page_obj.paginate_queryset(carLst, request)
        # 4. 返回带上一页/下一页连接的页面
        return page_obj.get_paginated_response(page_data)


class VisitorDetApi(APIView):
    # permission_classes = (IsAuthenticated,)
    # authentication_classes = [TeacherJWT,VisitorJWT,StudentJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        carId = request.GET.get("carId")
        car = Car.objects.get(id=carId)
        result["data"]["info"] = CarDetSerl(car).data
        return Response(result)


class CarEnterLstApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        page = request.GET.get("page")
        responseLst = ymiot_api.get_enter_car_list(6, page)
        if responseLst["code"] == 0:
            responseData = responseLst["data"]
            result["data"]["carLst"] = responseData["carLst"]
        else:
            responseMsg = responseLst["msg"]
            result["code"] = 500
            result["msg"] = responseMsg
        return Response(result)


class CarEnterDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        plate = request.GET.get("plate")
        startTime = (datetime.datetime.now() - datetime.timedelta(hours=24)).strftime(
            "%Y-%m-%d %H:%M:%S"
        )
        endTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        responseSingle = ymiot_api.get_enter_car_single(plate, startTime, endTime)
        if responseSingle["code"] == 0:
            responseData = responseSingle["data"]
            print(responseSingle["msg"])
            result["data"]["carLst"] = responseData["carLst"]
        else:
            responseMsg = responseSingle["msg"]
            result["code"] = 500
            result["msg"] = responseMsg
        return Response(result)


class CarOutLstApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        page = request.GET.get("page")
        responseLst = ymiot_api.get_out_car_list(6, page)
        if responseLst["code"] == 0:
            responseData = responseLst["data"]
            print(responseLst["msg"])
            result["data"]["carLst"] = responseData["carLst"]
        else:
            responseMsg = responseLst["msg"]
            result["code"] = 500
            result["msg"] = responseMsg
        return Response(result)


class CarOutDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        plate = request.GET.get("plate")
        startTime = (datetime.datetime.now() - datetime.timedelta(hours=24)).strftime(
            "%Y-%m-%d %H:%M:%S"
        )
        endTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        responseSingle = ymiot_api.get_out_car_single(plate, startTime, endTime)
        if responseSingle["code"] == 0:
            responseData = responseSingle["data"]
            print(responseSingle["msg"])
            result["data"]["carLst"] = responseData["carLst"]
        else:
            responseMsg = responseSingle["msg"]
            result["code"] = 500
            result["msg"] = responseMsg
        return Response(result)


class UnusualIndexApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 全部场内
        car_list = Car.objects.filter(status=3).exclude(enter_time=None)
        result["data"]["inCarCount"] = car_list.count()
        # 长期未出场车辆
        long_count = 0
        for car in car_list:
            enter_time = datetime.datetime.strptime(car.enter_time, "%Y-%m-%d %H:%M:%S")
            duration = datetime.datetime.now() - enter_time
            hours = (duration.seconds / 3600) + duration.days * 24
            if hours > 6:
                long_count += 1
            else:
                continue
        result["data"]["longCount"] = long_count
        return Response(result)


class UnusualLongLstApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 全部场内
        car_list = Car.objects.filter(status=3).exclude(enter_time=None)
        # 长期未出场车辆
        long_list = []
        for car in car_list:
            enter_time = datetime.datetime.strptime(car.enter_time, "%Y-%m-%d %H:%M:%S")
            duration = datetime.datetime.now() - enter_time
            hours = (duration.seconds / 3600) + duration.days * 24
            if hours > 6:
                long_item = {}
                long_item["car"] = CarDetSerl(car).data
                long_item["duration"] = int(hours)
                long_list.append(long_item)
        result["data"]["longList"] = long_list
        return Response(result)


class UnusualLongOutApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        car_id = request.data["car_id"]
        # 找到车辆
        car = Car.objects.get(id=car_id)
        # 更改状态
        car.status = 4
        car.out_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        car.out_gate_name = "异常车辆手动出场"
        car.save()
        # 教师邀请工单车辆出场状态同步
        cartask.teacher_carout_sync()
        # 访客申请工单车辆出场状态同步
        cartask.visitor_carout_sync()
        return Response(result)


class MthCarIdxApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        countLst = []
        # {"carTypeNo": "3651", "carTypeText": "临时车A"},
        for carType in carTypeList:
            countItm = {}
            countItm["carTypeNo"] = carType["carTypeNo"]
            countItm["carTypeText"] = carType["carTypeText"]
            countItm["count"] = MthCar.objects.filter(
                carTypeNo=carType["carTypeNo"]
            ).count()
            countLst.append(countItm)
        result["data"]["countLst"] = countLst
        return Response(result)


class MthCarLstApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        carTypeNo = request.GET.get("carTypeNo")
        print("carTypeNo")
        print(carTypeNo)
        if carTypeNo == "0":
            print("carTypeNo == 0")
            mthCarLst = MthCar.objects.all()
        else:
            print("else")
            mthCarLst = MthCar.objects.filter(carTypeNo=carTypeNo)
        # 1. 实例化分页器对象
        page_obj = pagination.PageNumberPagination()
        # 2. 使用自己配置的分页器调用分页方法进行分页
        page_data = page_obj.paginate_queryset(MthCarSerl(mthCarLst, many=True).data, request)
        # 4. 返回带上一页/下一页连接的页面
        return page_obj.get_paginated_response(page_data)


class MthCarDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        mthCarId = request.GET.get("mthCarId")
        mthCar = MthCar.objects.get(id=mthCarId)
        result["data"]["mthCar"] = MthCarSerl(mthCar).data
        return Response(result)


class MthCarAddApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        carTypeNo = request.data["carTypeNo"]
        userName = request.data["userName"]
        homeAddress = request.data["homeAddress"]
        mobNumber = request.data["mobNumber"]
        carNo = request.data["carNo"]
        personRes = ymiot_api.add_person(carTypeNo, userName, homeAddress, mobNumber)
        if personRes["code"] == 0:
            userNo = personRes["data"]["userNo"]
            carRes = ymiot_api.add_mthcar(carNo, userNo)
            if carRes["code"] == 0:
                try:
                    mthCar = MthCar.objects.get(carNo=carNo)
                except MthCar.DoesNotExist:
                    mthCar = MthCar()
                    mthCar.carNo = carNo
                mthCar.carTypeNo = carTypeNo
                mthCar.userNo = userNo
                mthCar.save()
            else:
                result["code"] = 500
                result["msg"] = "新增车辆失败"
        else:
            result["code"] = 500
            result["msg"] = "新增车主失败"
        return Response(result)


class MthCarSearchApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        carNo = request.data["carNo"]
        try:
            mthCar = MthCar.objects.get(carNo=carNo)
            result["data"]["carId"] = mthCar.id
            return Response(result)
        except MthCar.DoesNotExist:
            responseSingle = ymiot_api.search_mthcar(carNo)
            if responseSingle["code"] == 0:
                responseData = responseSingle["data"]
                print(responseSingle["msg"])
                count = responseData["count"]
                if count == 0:
                    result["code"] = 500
                    result["msg"] = "未找到该车辆"
                    return Response(result)
                else:
                    carDet = responseData["carDet"]
                    mthCar = MthCar()
                    mthCar.carNo = carDet["carNo"]
                    mthCar.carTypeNo = carDet["carTypeNo"]
                    mthCar.beginTime = carDet["beginTime"]
                    mthCar.endTime = carDet["endTime"]
                    mthCar.iusseTime = carDet["iusseTime"]
                    mthCar.userName = carDet["userName"]
                    mthCar.phone = carDet["phone"]
                    mthCar.homeAddress = carDet["homeAddress"]
                    mthCar.save()
                    result["data"]["carId"] = mthCar.id
                    return Response(result)
            else:
                responseMsg = responseSingle["msg"]
                result["code"] = 500
                result["msg"] = "未找到该车辆"
                return Response(result)


class MthCarChargeApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        carNo = request.data["carNo"]
        # 应该先去系统查？
        responseSearch = ymiot_api.search_mthcar(carNo)
        if responseSearch["code"] == 0:
            # 系统有
            # 先将系统数据库同步到本地
            responseSearchData = responseSearch["data"]
            try:
                mthCar = MthCar.objects.get(carNo=carNo)
            except MthCar.DoesNotExist:
                # 本地也没有
                mthCar = MthCar()
                mthCar.carNo = carNo
            responseSearchCar = responseSearchData["carDet"]
            mthCar.carNo = responseSearchCar["carNo"]
            mthCar.carTypeNo = responseSearchCar["carTypeNo"]
            mthCar.beginTime = responseSearchCar["beginTime"]
            mthCar.endTime = responseSearchCar["endTime"]
            mthCar.iusseTime = responseSearchCar["iusseTime"]
            mthCar.userName = responseSearchCar["userName"]
            mthCar.phone = responseSearchCar["phone"]
            mthCar.homeAddress = responseSearchCar["homeAddress"]
            mthCar.save()
            # 如果系统数据到2026就不管了
            if responseSearchCar["endTime"] == "2026-12-31 00:00:00":
                return Response(
                    {"code": 0, "msg": "车场系统同步成功", "data": {"carId": mthCar.id}}
                )
            # 开始充值
            resCharge = ymiot_api.charge_mthcar(mthCar.carNo)
            if resCharge["code"] == 0:
                # 充值成功
                beginTime = resCharge["data"]["beginTime"]
                endTime = resCharge["data"]["endTime"]
                # 同步本地数据
                mthCar.beginTime = beginTime
                mthCar.endTime = endTime
                mthCar.save()
                return Response(
                    {"code": 0, "msg": "充值成功", "data": {"carId": mthCar.id}}
                )
            else:
                return Response({"code": 500, "msg": "充值失败"})
        else:
            # 没有
            # 查本地数据库
            try:
                mthCar = MthCar.objects.get(carNo=carNo)
                # 添加到系统数据库
                # 1新增月租车用户
                resPerson = ymiot_api.add_person(
                    mthCar.carTypeNo, mthCar.userName, mthCar.homeAddress, mthCar.phone
                )
                if resPerson["code"] == 0:
                    userNo = resPerson["data"]["userNo"]
                    # 同步USERNO先
                    mthCar.userNo = userNo
                    mthCar.save()
                    # 2新增月租车
                    resAdd = ymiot_api.add_mthcar(carNo, userNo)
                    if resAdd["code"] == 0:
                        resSearch = ymiot_api.search_mthcar(carNo)
                        if resSearch["code"] == 0:
                            resSearchData = resSearch["data"]
                            # 同步本地数据库
                            resSearchCar = resSearchData["carDet"]
                            mthCar.carNo = resSearchCar["carNo"]
                            mthCar.carTypeNo = resSearchCar["carTypeNo"]
                            mthCar.beginTime = resSearchCar["beginTime"]
                            mthCar.endTime = resSearchCar["endTime"]
                            mthCar.iusseTime = resSearchCar["iusseTime"]
                            mthCar.userName = resSearchCar["userName"]
                            mthCar.phone = resSearchCar["phone"]
                            mthCar.homeAddress = resSearchCar["homeAddress"]
                            mthCar.save()
                            # 开始充值
                            resCharge = ymiot_api.charge_mthcar(mthCar.carNo)
                            if resCharge["code"] == 0:
                                # 充值成功
                                beginTime = resCharge["data"]["beginTime"]
                                endTime = resCharge["data"]["endTime"]
                                # 同步本地数据
                                mthCar.beginTime = beginTime
                                mthCar.endTime = endTime
                                mthCar.save()
                                return Response(
                                    {
                                        "code": 0,
                                        "msg": "充值成功",
                                        "data": {"carId": mthCar.id},
                                    }
                                )
                            else:
                                return Response({"code": 500, "msg": "充值失败"})
                        else:
                            return Response({"code": 500, "msg": "查询月租车信息失败"})
                    else:
                        return Response({"code": 500, "msg": "2新增月租车失败"})
                else:
                    return Response({"code": 500, "msg": "1新增月租车用户失败"})
            except MthCar.DoesNotExist:
                # 本地也没有
                return Response(
                    {"code": 404, "msg": "车辆既不在本地数据库，也不在系统数据库"}
                )
